﻿//创建时间: 2011-11-16
//创建作者: 李 城
//功能说明: 模板数据处理，继承  IDAL       
//最后修改: 2011-11-16

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using TRPOP.CMS.Template;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data.Common;
using TRPOP.Config;
using TRPOP.CMS.Model;
using System.Text.RegularExpressions;
using TRPOP.Common;
using TRPOP.CMS.Business;
using TRPOP.CMS.Plugin;
using System.IO;

namespace TRPOP.CMS.TemplateSQLServerDAL
{
    public class Helper
    {

        #region 基本属性

        public static string mSqlWhereForContent = " AND PubStatus= " + ((int)TRPOP.Common.PubStatus.EnumElement.Publish).ToString() + "  ";
        public static string mSqlWhereForNode = " AND ContentPubTypeId != " + ((int)TRPOP.Common.ContentPubType.EnumElement.NotOutPub).ToString();
        public static string mSqlFormat = " SELECT $TOP$ row_number() OVER (  $Orderby$   ) AS indexid  ,   * from  " +
                                  " ( " +
                                  "   {0}  " +
                                  " ) i  WHERE 1=1 " +
                                  " {1} ";
        public static string mContentColumns = string.Format("  , {0}.PubTime AS PublishDate,    {0}.TopWeight AS [top],     {0}.DisplayOrder AS Sort,  {0}.EliteWeight AS Pink ", SystemInfoHelper.getSystemInfo().DBprefixTableName + "_content_Content");

        /// <summary>
        ///   带列的 List sql
        /// </summary>
        public static string GetListBaseSQL
        {
            get
            {
                string strReturn = @" 
                          SELECT     $Top$
                          ContentTable.ContentId as IndexID
                          ,ContentTable.[ContentId]
                          ,ContentTable.[Status]
                          ,ContentTable.[PubStatus]
                          ,ContentTable.[NodeId]
                          ,ContentTable.[NodeContentSortId]
                          ,ContentTable.[ExtendId]
                          ,ContentTable.[ExtendTableName]
                          ,ContentTable.[Name]
                          ,ContentTable.[Url]
                          ,ContentTable.[ExtraUrl]
                          ,ContentTable.[TopWeight]
                          ,ContentTable.[EliteWeight]
                          ,ContentTable.[DisplayOrder]
                          ,ContentTable.[PubUserId]
                          ,ContentTable.[PubTime]
                          ,ContentTable.[AddUserId]
                          ,ContentTable.[AddTime]
                          ,ContentTable.[UpdateUserId]
                          ,ContentTable.[UpdateTime]
                          ,ContentTable.[Click]
                          ,ContentTable.[SEOTitle]
                          ,ContentTable.[SEOKey]
                          ,ContentTable.[SEODescription]
                          ,NodeTable.[Name] as NodeName
                          ,NodeTable.[Url] as NodeURL
                          ,ExtTable.*
                         FROM
                            [{0}_content_Content] as ContentTable,
                            [{0}_node_Node] as  NodeTable,
                            $ExtTable$ as ExtTable
                         WHERE
                                 ContentTable.Nodeid=NodeTable.Nodeid
                            AND  ExtTable.$ExtTable$id=ContentTable.ExtendId
                    " + mSqlWhereForContent;
                return string.Format(strReturn, SystemInfoHelper.getSystemInfo().DBprefixTableName);
            }
        }
        /// <summary>
        ///  不带列的 list sql
        /// </summary>
        public static string GetListBaseSQLWithNuColum
        {
            get
            {
                string strReturn = @" 
                          SELECT     $Top$
                               $Column$
                         FROM
                            [{0}_content_Content] as ContentTable,
                            [{0}_node_Node] as  NodeTable,
                            $ExtTable$ as ExtTable
                         WHERE
                                 ContentTable.Nodeid=NodeTable.Nodeid
                            AND  ExtTable.$ExtTable$id=ContentTable.ExtendId
                    " + mSqlWhereForContent;
                return string.Format(strReturn, SystemInfoHelper.getSystemInfo().DBprefixTableName);
            }
        }

        /// <summary>
        /// 分页情况下 外部嵌套的sql
        /// </summary>
        public static string GetListPagerSQL
        {
            get
            {
                return @"
                        select * from 
                            (
                            select  row_number() OVER ( $ORDERBY$  ) AS IndexFlag ,InfoTable.* 
                            from 
                            (
                                 $SQLEXEC$
                            ) InfoTable
                        ) tableTemp
                        where 1=1  $WHERE$
                       ";
            }
        }

        /// <summary>
        /// 获取list标签分页情况下所有信息的总数
        /// </summary>
        public static string GetListTotalCount
        {
            get
            {
                return string.Format(@"
                          select  count(0)                         
                          from {0}_content_Content as ContentTable, $ExtTable$    as        ExtTable                 
                          where  ExtendId=$ExtTable$id     
                        ", SystemInfoHelper.getSystemInfo().DBprefixTableName) + mSqlWhereForContent;
            }
        }

        #endregion

        #region 基本方法

        /// <summary>
        /// 对sql语句整体上外加分页sql
        /// </summary>
        /// <param name="strSQL"></param>
        /// <param name="strWhere"></param>
        public static void SqlFormat(ref string strSQL, string strWhere)
        {
            string strTop = "$TOP$";
            string strTopReplace = "$TOP$";
            Regex oReg = new Regex(@"top[\s]*(\d)+", RegexOptions.Multiline | RegexOptions.IgnoreCase);
            Match oMatch = oReg.Match(strSQL);
            if (oMatch.Success)
            {
                strTopReplace = oMatch.Value;
                strSQL = strSQL.Replace(strTopReplace, "");
            }
            else
                strTopReplace = "";
            string orderby = " order by  i.ContentId desc ";
            if (strSQL.ToLower().Contains("order"))
            {
                string strOrderby = strSQL.ToLower().Substring(strSQL.ToLower().LastIndexOf("order"));
                string strReg = @"order[\s]+?by[\s]+?[\w]+?([\s]+?[,][\w]+)*?[\s]+?((asc)|(desc))[\s]*?";
                Regex oRegex = new Regex(strReg, RegexOptions.Multiline | RegexOptions.IgnoreCase);
                Match oMatchTemp = oRegex.Match(strOrderby);
                if (oRegex.Match(strOrderby).Success)
                {
                    orderby = string.Format(oMatch.Value);
                }
            }
            strSQL = string.Format(mSqlFormat.Replace(strTop, strTopReplace).Replace("$Orderby$", orderby), strSQL, strWhere);
        }

        /// <summary>
        /// 对内容的基本限制SQL
        /// </summary>
        /// <param name="strWhere"></param>
        public static void SqlWhereForContent(ref string strWhere)
        {
            strWhere = "  " +
              (strWhere.IsEmpty() ? (mSqlWhereForContent) : (strWhere + mSqlWhereForContent));
        }

        /// <summary>
        /// 对结点的基本限制SQL
        /// </summary>
        /// <param name="strWhere"></param>
        public static void SqlWhereForNode(ref string strWhere)
        {
            strWhere = "  " +
              (strWhere.IsEmpty() ? (mSqlWhereForNode) : (strWhere + mSqlWhereForNode));
        }

        /// <summary>
        /// 替换cmsware固有的条件
        /// </summary>
        /// <param name="StrExe"></param>
        /// <returns></returns>
        public static string SqlWhereReplace(string StrExe)
        {
            return StrExe.ToLower()
                         .Replace("c.", "")
                         .Replace("i.", "")
                         .Replace("co.", "")
                         .Replace("!=''", " is not null ")
                //.Replace(" publishdate "," pubtime ")
                //.Replace(" [top] ", " topweight ")
                //.Replace(" sort ", " displayorder ")
                //.Replace(" pink ", " eliteweight ")
                         .Replace(" indexid ", " contentid ")
                //.Replace("unix_timestamp()", " DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE()) ")
                         ;
        }

        /// <summary>
        /// 获取SQL条件 排除
        /// </summary>
        /// <param name="strIngoreIds"></param>
        /// <returns></returns>
        public static string SqlWhereingoreContentID(string strIngoreIds)
        {
            string strIgnoreWhere = string.Empty;

            foreach (string tempfield in strIngoreIds.Split(','))
            {
                strIgnoreWhere += tempfield.ToInt() + ",";
            }

            if (strIgnoreWhere.Length > 0)
            {
                strIgnoreWhere = strIgnoreWhere.ClearLastChar();
                strIgnoreWhere = string.Format(" AND ContentId NOT IN ({0}) ", strIgnoreWhere);
            }
            return strIgnoreWhere;
        }

        #endregion

        #region  URL转换  1 根据内容id，转换内容里的URL  2 根据datatable 处理资源字段

        /// <summary>
        /// 根据内容id，将 内容字段里的 ="/imgurl"   ='/imgurl' 换转 为 ="http://....imgurl"   ='http://...../imgurl' , http这类的域名信息从 _content_ContentUpFile 库里获取
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="strIndexIds"></param>
        /// <returns></returns>
        public static string ConvertContentUrlByIndexID(string strContent, string strIndexIds)
        {
            //如果不包含 ="/  并且也不包含 ='/  ，则认为不需要经过 地址转换这个方法
            if (strContent.Contains("=\"/") == false && strContent.Contains("='/") == false)
                return strContent;

            strIndexIds = strIndexIds.Trim(", ".ToArray());

            if (!strIndexIds.IsEmpty())
            {
                foreach (DataRow oTempRow in new ContentUpFileManage().GetDtListByCondition(0, " [FileRoot] ,[FileURL] ", " AND CHARINDEX('http:','00'+[FileURL] )>0 AND  contentid in ( " + strIndexIds + " ) ", "").Rows)
                {
                    strContent = strContent.Replace("=\"" + oTempRow["FileRoot"].ToString().Trim() + "\"", "=\"" + oTempRow["FileURL"].ToString().Trim() + "\"")
                                           .Replace("='" + oTempRow["FileRoot"].ToString().Trim() + "'", "='" + oTempRow["FileURL"].ToString().Trim() + "'");
                }
            }

            return strContent;
            /*
            ImgResourceHelper oImgResourceHelper = new ImgResourceHelper();
            oImgResourceHelper.Init(strContent, strIndexIds);
            return oImgResourceHelper.GetSourceContent(strContent, ImgResourceType.Normal);
            */ 
        }

        public const string strFindPic = "[=][" + "\"" + @"'][\s]*(?<file>[/][\S]*[.]((png)|(bmp)|(jpg)|(jpeg)|(gif)|(psd)))[" + "\"" + "']";

        /// <summary>
        /// 内容页提取当前内容时使用，将已得到的数据源里的主内容字段图片进行转换，增加图片类型集合字段,这样可适用于多种类型的页面
        /// </summary>
        /// <param name="oDataRow"></param>
        /// <param name="strMainField"></param>
        public static void ConvertContentUrl(DataRow oDataRow, string strMainField)
        {
            string strAllImgs = " 1<>1 ";

            Dictionary<string, string> oDictionary = new Dictionary<string, string>();
            string strKey = "";
            foreach (Match oMatch in new Regex(strFindPic, RegexOptions.IgnoreCase | RegexOptions.Multiline).Matches(oDataRow[strMainField].ToString()))
            {
                if (oMatch.Success && oDictionary.Keys.Contains((strKey = oMatch.Groups["file"].Value.Trim())) == false)
                {
                    oDictionary.Add(strKey, strKey);
                    strAllImgs += " OR [FileRoot]='" + strKey.SQLFilter() + "' ";
                }
            }

            Dictionary<string, Dictionary<TRPOP.Common.ImgType.ImgResourceType, string>> oDic = new Dictionary<string, Dictionary<Common.ImgType.ImgResourceType, string>>();

            strAllImgs = " AND ( " + strAllImgs + " ) ";
            foreach (DataRow oTempRow in new ContentUpFileManage().GetDtListByCondition(0, " [FileRoot] ,[FileURL] ", " AND CHARINDEX('http:','00'+[FileURL] )>0  " + strAllImgs, "").Rows)
            {
                if (oDic.ContainsKey(oTempRow["FileRoot"].ToString().Trim()) == false)
                {
                    oDic.Add(oTempRow["FileRoot"].ToString().Trim(), new Dictionary<Common.ImgType.ImgResourceType, string>());
                    oDic[oTempRow["FileRoot"].ToString().Trim()].Add(Common.ImgType.ImgResourceType.Normal, oTempRow["FileURL"].ToString().Trim());
                    oDataRow[strMainField] = oDataRow[strMainField].ToString().Replace(oTempRow["FileRoot"].ToString(), oTempRow["FileURL"].ToString().Trim());
                }
            }

            oDataRow.Table.Columns.Add(TRPOP.Common.ImgType.strImgResourceCollectionColumnName, oDic.GetType());
            oDataRow[TRPOP.Common.ImgType.strImgResourceCollectionColumnName] = oDic;
        }

        /// <summary>
        ///  处理资源字段的里的地址
        /// </summary>
        /// <param name="oDt"></param>
        public static void PSNSourceURlFilter(DataTable oDt)
        {
            PSNSourceURlFilterForContent(oDt);
        }

        /// <summary>
        /// 处理资源字段的里的地址
        /// </summary>
        /// <param name="oDataTable"></param>
        /// <returns></returns>
        public static string PSNSourceURlFilterForContent(DataTable oDataTable)
        {
            string strMainColumReturn = string.Empty;
            string strNodeid = string.Empty;

            //如果数据为空 或 不包含nodeid字段,则直接退出
            if (oDataTable == null || oDataTable.Rows.Count <= 0 || (oDataTable.Columns.Contains("NodeId") == false))
                return strMainColumReturn;

            strNodeid = oDataTable.Rows[0]["NodeId"].ToString();

            Dictionary<string, string> dicSourField = new Dictionary<string, string>();
            NodeManage oNodeManage = new NodeManage();

            // 将第一个nodeid作为获取NodeInfo的依据
            NodeInfo mNodeInfo = oNodeManage.GetInfoById(strNodeid.ToInt());

            //如果结点实体为空，则没有办法找到 所属模型，即没有办法找到资源字段，所以直接跳出
            if (mNodeInfo == null)
                return strMainColumReturn;

            // 获取资源字段，将其写入Dictionary(dicSourField)中
            List<ModelFieldInfoWithTableName> mModelFieldList = new ModelFieldManage().GetWithTableNameListByModelId(mNodeInfo.ModelId);
            if (mModelFieldList == null) // 无法找到资源字段，则直接跳出
            {
                return strMainColumReturn;
            }
            foreach (ModelFieldInfoWithTableName info in mModelFieldList)
            {
                if (info.IsMainField)
                    strMainColumReturn = info.FieldName;
                if (info.FieldInputPicker == FieldInputPickerType.AttachPicker || info.FieldInputPicker == FieldInputPickerType.ImgPicker)
                {
                    dicSourField.Add(info.FieldName, info.FieldTypeStr);
                }
            }
            if (dicSourField.Count <= 0)// 没有资源字段，则直接跳出
                return strMainColumReturn;

            // 采用结点缓存psnsourceURL来替换以/开头的资源字段
            SerializableDictionary<string, string> oDicNodeURLForSourcePSN = oNodeManage.GetNodeURLForSourcePSN();
            ContentUpFileManage oContentUpFileManage = new ContentUpFileManage();
            foreach (DataRow row in oDataTable.Rows)
            {
                if (!oDicNodeURLForSourcePSN.ContainsKey(row["NodeId"].ToString().Trim() + "_PSNSourceRoot"))
                {
                    oDicNodeURLForSourcePSN = oNodeManage.SaveNodeURLForSourcePSN(oNodeManage.GetInfoById(int.Parse(row["nodeid"].ToString())));
                }
                foreach (string key in dicSourField.Keys)
                {
                    if (row[key] != null &&
                        row[key].ToString().IsEmpty() == false &&
                        row[key].ToString().Trim().StartsWith("/") &&
                        oDicNodeURLForSourcePSN.ContainsKey(row["NodeId"].ToString().Trim() + "_PSNSourceRoot")
                        )
                    {
                        if (row[key].ToString().Contains(oDicNodeURLForSourcePSN[row["nodeid"].ToString().Trim() + "_PSNSourceRoot"]))
                        {
                            row[key] = row[key].ToString().Replace(oDicNodeURLForSourcePSN[row["nodeid"].ToString().Trim() + "_PSNSourceRoot"], oDicNodeURLForSourcePSN[row["nodeid"].ToString().Trim() + "_PSNSourceRootURL"]);
                        }
                        else//如果不包含，可能数据出现了异常，则查询数据库，查看存在数据库里的地址
                        {
                            ContentUpFileInfo otempInfo = oContentUpFileManage.GetInfoByFileRoot(row[key].ToString().Trim());
                            if (otempInfo != null && otempInfo.FileURL.Trim().ToLower().StartsWith("http://"))
                            {
                                row[key] = otempInfo.FileURL.Trim();
                            }
                        }
                    }
                }
            }
            return strMainColumReturn;
        }

        #endregion

        #region 获取结点集合的辅助方法
        public static string GetWhereSqlForNodeList(bool blnNodeguid, string strNodeguid)
        {
            string strWhereForSelectNodeid = string.Empty;
            if (blnNodeguid)
            {
                foreach (string strNodeid in strNodeguid.Split(','))
                {
                    strWhereForSelectNodeid += "'" + strNodeid.Replace("'", "").Trim() + "',";
                }
                if (strWhereForSelectNodeid.Length > 0)
                    strWhereForSelectNodeid = strWhereForSelectNodeid.ClearLastChar();

                strWhereForSelectNodeid = string.Format(" AND [KeyWord] IN ({0}) ", strWhereForSelectNodeid);

            }
            else
            {
                foreach (string strNodeid in strNodeguid.Split(','))
                {
                    strWhereForSelectNodeid += strNodeid.ToInt() + ",";
                }
                if (strWhereForSelectNodeid.Length > 1)
                    strWhereForSelectNodeid = strWhereForSelectNodeid.ClearLastChar();

                strWhereForSelectNodeid = string.Format(" AND [nodeid] IN ({0}) ", strWhereForSelectNodeid);

            }
            return strWhereForSelectNodeid;
        }
        #endregion

        #region 结点信息 获取 Navigation
        public static void SaveInfoForNavigation(DataRow oSourceDt)
        {
            if (oSourceDt == null || oSourceDt.Table.Columns.Contains("NodeId") == false)
                return;

            int intNodeid = 0;
            DataTable DtTest = new DataTable();
            oSourceDt.Table.Columns.Add("Navigation", DtTest.GetType());
            NodeManage m_NodeManage = new NodeManage();
            intNodeid = oSourceDt["NodeId"].ToString().ToInt();
            if (intNodeid <= 0)
                return;
            DataTable oDt = new DataTable();
            oDt.Columns.Add("NodeID");
            oDt.Columns.Add("Name");
            oDt.Columns.Add("URL");
            getNodeParentLoop(oDt, intNodeid, m_NodeManage);
            oSourceDt["Navigation"] = oDt;
        }
        // 获取结点的所有父节点
        public static void getNodeParentLoop(DataTable oDt, int intNodeid, NodeManage m_NodeManage)
        {
            if (intNodeid > 0)
            {
                NodeInfo m_ParentNodeInfo = m_NodeManage.GetInfoById(intNodeid);
                if (m_ParentNodeInfo != null)
                {
                    DataRow oNewRow = oDt.NewRow();
                    oNewRow["NodeID"] = m_ParentNodeInfo.NodeId;
                    oNewRow["Name"] = m_ParentNodeInfo.Name;
                    oNewRow["URL"] = m_ParentNodeInfo.Url;
                    oDt.Rows.InsertAt(oNewRow, 0);
                    if (m_ParentNodeInfo.ParentId > 0)
                    {
                        getNodeParentLoop(oDt, m_ParentNodeInfo.ParentId, m_NodeManage);
                    }
                }
            }
        }
        #endregion

        #region 获取扩展表名
        
        /// <summary>
        /// 根据结点id是获取扩展表名
        /// </summary>
        /// <param name="nodeids"></param>
        /// <returns></returns>
        public static string GetExtendTableName(string nodeids)
        {
            string strWhere = " AND NodeId IN (" + nodeids + ") ";
            return GetExtendTableNameByNodeSQL(strWhere);
        }
        /// <summary>
        /// 根据条件获取扩展表名
        /// </summary>
        /// <param name="strNodeWhere"></param>
        /// <returns></returns>
        public static string GetExtendTableNameByNodeSQL(string strNodeWhere)
        {
            DataSet ds = new DataSet();
            SqlDatabase odbDataBase = new SqlDatabase(SystemInfoHelper.getSystemInfo().CMSDataBaseConnection);
            DbCommand odbCommand = null;
            string strSQl = @"
                        SELECT TableName 
                        FROM {0}_model_Model 
                        WHERE  ModelId IN (
                            SELECT ModelId  FROM {0}_node_Node WHERE 1=1 {1}
                        )
                        ";
            odbCommand = odbDataBase.GetSqlStringCommand(
                             string.Format(strSQl, SystemInfoHelper.getSystemInfo().DBprefixTableName, strNodeWhere)
                         );
            try
            {
                using (ds = odbDataBase.ExecuteDataSet(odbCommand))
                {
                    if (ds.Tables[0].Rows.Count > 0)
                        return ds.Tables[0].Rows[0][0].ToString();
                    else
                        return "";
                }
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
        }

        /// <summary>
        /// 根据tableid 获取表名
        /// </summary>
        /// <param name="strTableid"></param>
        /// <returns></returns>
        public static string GetExtendTableNameByTableId(string strTableid)
        {
            string strTableName = string.Empty;

            int intTableid = 0;
            int.TryParse(strTableid, out intTableid);
            if (intTableid > 0)
            {
                using (DataSet oDataSet = BaseDAL.mICommonDAL.GetDataSetByReader(string.Format("SELECT TOP 1 [TableName]  FROM {0}_model_Model WHERE  [ModelId]={1} ", SystemInfoHelper.getSystemInfo().DBprefixTableName, intTableid), SystemInfoHelper.getSystemInfo().CMSDataBaseConnection))
                {
                    if (oDataSet.Tables[0].Rows.Count > 0)
                        strTableName = oDataSet.Tables[0].Rows[0][0].ToString();
                }
            }

            return strTableName;
        }
        #endregion

        #region 根据给定的关键字拼接SQL条件
        /// <summary>
        /// 根据给定的关键字拼接SQL条件
        /// </summary>
        /// <param name="strField"></param>
        /// <param name="strKeywords"></param>
        /// <param name="strSeparator"></param>
        /// <param name="blnExact"></param>
        /// <returns></returns>
        public static string GetSearchWhere(string strField, string strKeywords, string strSeparator, bool blnExact)
        {
            if (strField.IsEmpty() == false && strKeywords.IsEmpty() == false && strSeparator.IsEmpty() == false)
            {
                StringBuilder strBuilder = null;
                if (blnExact)
                {
                    strBuilder = new StringBuilder(" 1=1 ");
                }
                else
                {
                    strBuilder = new StringBuilder(" 1<>1 ");
                }
                foreach (string strFieldTemp in strField.Split(strSeparator.Trim().ToCharArray()[0]))
                {
                    if (strFieldTemp.IsEmpty() == false)
                    {
                        foreach (string strTemp in strKeywords.Split(strSeparator.Trim().ToCharArray()[0]))
                        {
                            if (blnExact)
                            {
                                strBuilder.Append(string.Format(" and {0}= '{1}'", strFieldTemp, strTemp.Replace("'", "''")));
                            }
                            else
                                strBuilder.Append(string.Format(" or {0} like '%{1}%'", strFieldTemp, strTemp.Replace("'", "''")));
                        }
                    }
                }
                return "( " + strBuilder.ToString() + ")";
            }
            else
                return string.Empty;
        }
        #endregion 

        #region 根据指定的Table、nodeid 加nodid的where条件 例如" and nodeid in (...) "

        public static string SqlWhereForNodeByIdAndTableName(string strNodeids, bool blnSubNodeid, string strTableName)
        {

            string strNodeSQLwhere = string.Empty;//and nodeid in (1,2)

            if (strTableName.IsEmpty() == false)
            {
                strTableName = strTableName + ".";
            }

            if (strNodeids.Contains(","))
            {
                foreach (string strNodeid in strNodeids.Split(','))
                {
                    strNodeSQLwhere += (strNodeid).ToInt() + ",";
                }
                if (strNodeSQLwhere.Length > 0)
                    strNodeSQLwhere = strNodeSQLwhere.ClearLastChar();
                strNodeSQLwhere = string.Format(" AND {0}NodeId in ({1}) ", strTableName,strNodeSQLwhere);
            }
            else if (blnSubNodeid == false)
            {
                strNodeSQLwhere = string.Format(" AND {0}NodeId ={1} ", strTableName, strNodeids.ToInt());
            }
            else
            {
                List<NodeInfoWithLevel> list = new NodeManage().GetNodeListTree(strNodeids.ToInt(), 1, mSqlWhereForNode, true);
                foreach (NodeInfoWithLevel oinfo in list)
                {
                    strNodeSQLwhere += oinfo.NodeId.ToString() + ",";
                }
                if (strNodeSQLwhere.Length > 0)
                {
                    strNodeSQLwhere += strNodeids;
                }
                else
                {
                    strNodeSQLwhere = strNodeids;
                }
                strNodeSQLwhere = string.Format(" AND {0}NodeId in ({1}) ", strTableName, strNodeSQLwhere);
            }

            return strNodeSQLwhere;
        }
        #endregion

    }
}
